﻿using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using SenileCoderMvc.Library.Models;

namespace SenileCoderMvc.Library.DataAccess
{
    public class SenilitySessionFactory : IMakesSessionFactories
    {
        private readonly object threadLock = new object();
        private ISessionFactory sessionFactory;
        private readonly string connectionString;

        public SenilitySessionFactory(string connectionString)
        {
            this.connectionString = connectionString;
        }

        public ISessionFactory GetSessionFactory()
        {
            if (sessionFactory == null)
            {
                lock (threadLock)
                {
                    sessionFactory = Fluently.Configure()
                        .Database(MsSqlConfiguration.MsSql2008.ConnectionString(connectionString))
                        .Mappings(map => map.FluentMappings.AddFromAssemblyOf<CodeSnippet>())
                        .BuildConfiguration()
                        .BuildSessionFactory();
                }
            }

            return sessionFactory;
        }
    }
}
